package com.huluobo.a2307douyindemo.setting

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.google.gson.Gson
import com.huluobo.a2307douyindemo.R
import com.huluobo.a2307douyindemo.databinding.ActivitySettingBinding
import com.huluobo.a2307douyindemo.utils.ImageUtils
import com.huluobo.lib_base.bean.UserBean
import com.huluobo.lib_base.event.MessageEvent
import com.huluobo.lib_base.mvvm.BaseActivity
import com.huluobo.lib_base.net.Const
import com.wildma.pictureselector.PictureBean
import com.wildma.pictureselector.PictureSelector
import dagger.hilt.android.AndroidEntryPoint
import org.greenrobot.eventbus.EventBus

@AndroidEntryPoint
class SettingActivity : BaseActivity<ActivitySettingBinding, SettingViewModel>() {
    private val userBean = Gson().fromJson(SPUtils.getInstance().getString(Const.KEY_USER), UserBean::class.java)
    override fun initData() {
        vm.uploadSuccess.observe(this) {
            ToastUtils.showLong("上传成功")
            ImageUtils.loadImage(this, it, binding.settingUserIconIv)
            EventBus.getDefault().post(MessageEvent(it))
        }
    }

    override fun initView() {
        //通过UserBean赋值头像
        ImageUtils.loadImage(this, userBean.icon, binding.settingUserIconIv)

        binding.settingUserIconIv.setOnClickListener {
            selectPic()
        }

        binding.settingUserIconTv.setOnClickListener {
            selectPic()
        }
    }

    private fun selectPic() {
        PictureSelector.create(this, PictureSelector.SELECT_REQUEST_CODE).selectPicture()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        //同时判断请求码和返回码
        if (requestCode == PictureSelector.SELECT_REQUEST_CODE && resultCode == RESULT_OK) {
            //获取bundle
            val bundle = data?.extras
            //通过bundle获取图片对象
            val pictureBean = bundle?.getParcelable(PictureSelector.PICTURE_RESULT) as PictureBean?
            //从图片对象中拿到赌赢的图片路径
            val path = pictureBean?.path
            if (!path.isNullOrEmpty()) {
                vm.uploadIcon(path)
            } else {
                ToastUtils.showLong("图片读取错误")
            }
        }
    }
}